import { Component, Vue, Inject } from 'vue-property-decorator';

import dayjs from 'dayjs';
import { DATE_TIME_LONG_FORMAT } from '@/shared/date/filters';

import AlertService from '@/shared/alert/alert.service';

import CourseService from '@/entities/course/course.service';
import { ICourse } from '@/shared/model/course.model';

import StudentService from '@/entities/student/student.service';
import { IStudent } from '@/shared/model/student.model';

import TeacherService from '@/entities/teacher/teacher.service';
import { ITeacher } from '@/shared/model/teacher.model';

import { IUserClass, UserClass } from '@/shared/model/user-class.model';
import UserClassService from './user-class.service';

const validations: any = {
  userClass: {
    classId: {},
    startTime: {},
    endTime: {},
    classNumber: {},
    classStatus: {},
  },
};

@Component({
  validations,
})
export default class UserClassUpdate extends Vue {
  @Inject('userClassService') private userClassService: () => UserClassService;
  @Inject('alertService') private alertService: () => AlertService;

  public userClass: IUserClass = new UserClass();

  @Inject('courseService') private courseService: () => CourseService;

  public courses: ICourse[] = [];

  @Inject('studentService') private studentService: () => StudentService;

  public students: IStudent[] = [];

  @Inject('teacherService') private teacherService: () => TeacherService;

  public teachers: ITeacher[] = [];
  public isSaving = false;
  public currentLanguage = '';

  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (to.params.userClassId) {
        vm.retrieveUserClass(to.params.userClassId);
      }
      vm.initRelationships();
    });
  }

  created(): void {
    this.currentLanguage = this.$store.getters.currentLanguage;
    this.$store.watch(
      () => this.$store.getters.currentLanguage,
      () => {
        this.currentLanguage = this.$store.getters.currentLanguage;
      }
    );
  }

  public save(): void {
    this.isSaving = true;
    if (this.userClass.id) {
      this.userClassService()
        .update(this.userClass)
        .then(param => {
          this.isSaving = false;
          this.$router.go(-1);
          const message = 'A UserClass is updated with identifier ' + param.id;
          return this.$root.$bvToast.toast(message.toString(), {
            toaster: 'b-toaster-top-center',
            title: 'Info',
            variant: 'info',
            solid: true,
            autoHideDelay: 5000,
          });
        })
        .catch(error => {
          this.isSaving = false;
          this.alertService().showHttpError(this, error.response);
        });
    } else {
      this.userClassService()
        .create(this.userClass)
        .then(param => {
          this.isSaving = false;
          this.$router.go(-1);
          const message = 'A UserClass is created with identifier ' + param.id;
          this.$root.$bvToast.toast(message.toString(), {
            toaster: 'b-toaster-top-center',
            title: 'Success',
            variant: 'success',
            solid: true,
            autoHideDelay: 5000,
          });
        })
        .catch(error => {
          this.isSaving = false;
          this.alertService().showHttpError(this, error.response);
        });
    }
  }

  public convertDateTimeFromServer(date: Date): string {
    if (date && dayjs(date).isValid()) {
      return dayjs(date).format(DATE_TIME_LONG_FORMAT);
    }
    return null;
  }

  public updateInstantField(field, event) {
    if (event.target.value) {
      this.userClass[field] = dayjs(event.target.value, DATE_TIME_LONG_FORMAT);
    } else {
      this.userClass[field] = null;
    }
  }

  public updateZonedDateTimeField(field, event) {
    if (event.target.value) {
      this.userClass[field] = dayjs(event.target.value, DATE_TIME_LONG_FORMAT);
    } else {
      this.userClass[field] = null;
    }
  }

  public retrieveUserClass(userClassId): void {
    this.userClassService()
      .find(userClassId)
      .then(res => {
        res.startTime = new Date(res.startTime);
        res.endTime = new Date(res.endTime);
        this.userClass = res;
      })
      .catch(error => {
        this.alertService().showHttpError(this, error.response);
      });
  }

  public previousState(): void {
    this.$router.go(-1);
  }

  public initRelationships(): void {
    this.courseService()
      .retrieve()
      .then(res => {
        this.courses = res.data;
      });
    this.studentService()
      .retrieve()
      .then(res => {
        this.students = res.data;
      });
    this.teacherService()
      .retrieve()
      .then(res => {
        this.teachers = res.data;
      });
  }
}
